<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;

/**
 * 在线起名接口
 * @ApiWeigh (91)
 */
class Qiming extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 在线起名
     * 
     * @ApiTitle    (在线起名)
     * @ApiSummary  (根据用户信息进行在线起名)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/qiming/index)
     * 
     * @ApiParams   (name="surname", type="string", required=true, description="姓氏，如：张")
     * @ApiParams   (name="sex", type="integer", required=true, description="性别：0=男，1=女")
     * @ApiParams   (name="namewords", type="integer", required=true, description="姓名字数：2=两个字,3=三个字")
     * @ApiParams   (name="fix_mid_name", type="string", required=false, description="固定中间字(单字)，如：朝")
     * @ApiParams   (name="page", type="integer", required=false, description="显示哪一页的记录", default=1)
     * @ApiParams   (name="limit", type="integer", required=false, description="每一页显示多少条记录，最大不超过150", default=10)
     * 
     * @ApiReturn   ({
        "code": 1,
        "msg": "获取成功",
        "time": "1677123456",
        "data": {
          "list": [                         // 姓名列表
            "张哲语",
            "张智远",
            "张泽宇",
            // ...更多姓名
          ]
        }
      })
     */
    public function index()
    {
        $params = [
            'surname' => $this->request->post('surname', ''),
            'sex' => $this->request->post('sex', 0, 'intval'),
            'namewords' => $this->request->post('namewords', 2, 'intval'),
            'fix_mid_name' => $this->request->post('fix_mid_name', ''),
            'page' => $this->request->post('page', 1, 'intval'),
            'limit' => $this->request->post('limit', 150, 'intval')
        ];

        // 必填参数验证
        $required = ['surname', 'sex', 'namewords'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if (!in_array($params['namewords'], [2, 3])) {
            $this->error(__('Invalid namewords value'));
        }
        if (!empty($params['fix_mid_name']) && mb_strlen($params['fix_mid_name']) != 1) {
            $this->error(__('Invalid fix_mid_name value'));
        }

        // 验证limit参数
        if ($params['limit'] > 150) {
            $this->error(__('Parameter limit cannot exceed 150'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Dafen/qiming', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '在线起名失败');
            }
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }
}